package com.xj.util;

/**
 * User: bjxiajun
 * Date: 14-3-7
 * Time: 下午4:03
 */
public class BinaryToString {
    public static void main(String[] args) {
        BinaryToString.test();
    }

    public static void test() {
        /*将2进制数组转成字符串*/
        String str = "我在中国";
        byte[] bytes = str.getBytes();
        StringBuffer sb = new StringBuffer();
        for (byte b : bytes) {
            int i = b & 0xFF;
            if (i < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(i));
        }
        System.out.println(sb.toString());
        /*将字符串转成字符串2进制数组*/
        String bstr = sb.toString();
        char[] chars = bstr.toCharArray();
        byte[] bs = new byte[chars.length / 2];
        for (int i = 0; i < chars.length; i += 2) {
            if (chars[i] == '0') {
                int s = chars[i + 1];
                bs[i / 2] = (byte) (s & 0xFF);
            } else {
                String ss = bstr.substring(i, i + 2);
                int s = Integer.parseInt(ss,16);
                bs[i / 2] = (byte) (s & 0xFF);
            }
        }
        System.out.println(new String(bs));
    }
}
